package com.hoan.component.kotlin

import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.newSingleThreadContext
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import java.lang.Math.log
import kotlin.system.measureTimeMillis

/**
 *
 *
 * @author chenqiang
 * @date  2024/5/19
 */
fun main() {

    //-------------5
    /*runBlocking<Unit> {
        launch {
            println("main runBlocking")
        }
        launch(Dispatchers.Default) {
            println("Default")
            launch(Dispatchers.Unconfined) {
                println("Unconfined 1")
            }
        }
        launch(Dispatchers.IO) {
            println("IO")
            launch(Dispatchers.Unconfined) {
                println("Unconfined 2")
            }
        }
        launch(newSingleThreadContext("MyOwnThread")) {
            println("newSingleThreadContext")
            launch(Dispatchers.Unconfined) {
                println("Unconfined 4")
            }
        }
        launch(Dispatchers.Unconfined) {
            println("Unconfined 3")
        }
        GlobalScope.launch {
            println("GlobalScope")
        }
    }*/


    //----------4
    /*val time = measureTimeMillis {
        runBlocking {
            val asyncA = async {
                delay(3000)
                1
            }
            val asyncB = async {
                delay(4000)
                2
            }
            println(asyncA.await() + asyncB.await())
        }
    }
    println(time)*/

    //------------3
    /*GlobalScope.launch(Dispatchers.IO) {
        delay(600)
        println("GlobalScope")
    }
    runBlocking {
        delay(500)
        println("runBlocking")
    }
    //主动休眠两百毫秒，使得和 runBlocking 加起来的延迟时间多于六百毫秒
    Thread.sleep(200)
    println("after sleep")*/


    //-----------2
    /*GlobalScope.launch {
        delay(1000)
        //DefaultDispatcher-worker-1        默认 IO
        println(Thread.currentThread().name)
    }

    //主动休眠两秒，防止 JVM 过快退出
    Thread.sleep(2000)
    println(Thread.currentThread().name)*/

    //-----------1
     println("start")
     GlobalScope.launch {
         launch {
             delay(400)
             println("launch A")
         }
         launch {
             delay(300)
             println("launch B")
         }
         println("GlobalScope")
     }
     println("end")
     Thread.sleep(500)


}